# -*- coding: utf-8 -*-

"""
Author:NoamaNelson
Date:2019-11-15
Description:Reading video conversion to picture and save
参考自：https://blog.csdn.net/NoamaNelson/article/details/103078872和
https://blog.csdn.net/weixin_41528941/article/details/90900945
"""

import cv2
import numpy as np
from formatConverter import integratedOperation
import time
from openCV_PNG import save
# from formatConverter import pngquantOperation


class CamaroCap(object):
    """ 打开视频流 """

    def __init__(self, path):
        self.cap = cv2.VideoCapture(path)  # 视频路径，直接把脚本和视频放在同一个目录下最好，也可以指定对应的视频路径
        self.path = path
        self.re = "./resources/"

    """ 图片信息打印 """

    def get_image_info(self, image):
        print("图片位置：" + self.path)
        print(type(image))
        print(image.shape)
        print(image.size)
        print(image.dtype)
        pixel_data = np.array(image)
        print(pixel_data)

    """ 逐帧读取数据并保存图片到本地制定位置 """

    def Camaro_image(self, frameS=3, outF=".png", isUseSave=False, isLongC=True, is100=True):
        i = 0
        n = 1  # 计数
        timeF = frameS  # 视频帧计数间隔频率
        while 1:

            ret, frame = self.cap.read()  # ret：True或者False，代表有没有读取到图片;frame：表示截取到一帧的图片
            if ret is False:
                break

            if n % timeF != 0:  # 每隔timeF帧进行存储操作
                i += 1
                print(i)
                if isUseSave:
                    save("./resources/" + str(i) + outF, frame, 9)
                else:
                    cv2.imwrite("./resources/" + str(i) + outF, frame)  # 存储为图像
            n += 1
            cv2.waitKey(1)

            #
            # if frame % frameS == 0:
            #
            #     # self.get_image_info(frame)  # print("打印图片信息") 注意：调试的时候可以打开，如果是一直运行程序，建议把这行代码注释掉，避免影响内存占用
            #
            #     # cv2.imshow('capture', frame)  # 展示图片
            #
            #     cv2.imwrite("./resources/" + str(i) + ".jpg", frame)  # 保存图片
            #     i += 1

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

            if is100:
                if i == 100:
                    break

            # if i == 2000:
            #     break

        if isLongC:
            integratedOperation("./resources/")
        # pngquantOperation("./resources/")

    def zip(self):
        integratedOperation(self.re)


if __name__ == '__main__':
    t1 = time.time()
    outmasages = CamaroCap("./resources/ThemeVdo.mp4")

    outmasages.Camaro_image()  # 调用摄像头outF=".jpg" is100=False

    # outmasages.zip()

    outmasages.cap.release()  # 释放对象和销毁窗口
    cv2.destroyAllWindows()
    t2 = time.time()
    print("用时：" + str(t2 - t1))
